package com.dongdong.bookstore.common.exception;

import com.dongdong.bookstore.common.api.ResultData;
import com.dongdong.bookstore.common.api.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author chiangkai
 * @date 2021-09-17
 * @email chiangkk@163.com
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    /**
     * 自定义异常处理
     * @param
     * @return
     */
    @ExceptionHandler(value = ApiException.class)
    public ResultData<String> custom(Exception e){
        return ResultData.fail(e.getMessage());
    }

    /**
     * 404处理
     * @param
     * @return
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResultData<String> exceptionNotFound(NoHandlerFoundException e){
        log.info("找不到页面 ex={}", e.getMessage(), e);
        String message = "请求接口不存在。请求方式："+e.getHttpMethod()+",请求路径:"+e.getRequestURL();
        return ResultData.fail(ReturnCode.RC404.getCode(),
                message);
    }

    /**
     * 空指针异常处理
     * @param
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ResultData<String> nullPointerException(Exception e){
        log.error("空指针异常 ex={}", e.getMessage(), e);
        return ResultData.fail(e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultData<HashMap<String, Object>> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getDefaultMessage();
                map.put("description","错误字段");
                map.put("ErrorFiled",fieldError.getField());
            }
        }
        return ResultData.validateFailed(message,map);
    }

    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ResultData<String> handleValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return ResultData.validateFailed(message);
    }

    /**
     * 默认全局异常处理。
     * @param e the e
     * @return ResultData
     */
    @ExceptionHandler(Exception.class)
    public ResultData<String> exception(HttpServletRequest req,Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return ResultData.fail(e.getMessage());
    }


}
